"""
统合配置，兼容主入口与 api_gateway 的读取需求
"""
import os
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    # 应用基础
    APP_NAME: str = "MAESS"
    APP_VERSION: str = "1.0.0"
    APP_HOST: str = "0.0.0.0"
    APP_PORT: int = 8000
    APP_DEBUG: bool = True
    APP_ENV: str = "development"
    APP_SECRET_KEY: str = "maess-secret-key-for-development"
    ENVIRONMENT: str = "development"

    # CORS
    CORS_ORIGINS: list = ["http://localhost:5173", "http://127.0.0.1:5173"]

    # 日志
    LOG_LEVEL: str = "INFO"

    # 数据库 - 使用SQLite进行测试
    DATABASE_URL: str = "sqlite+aiosqlite:///./maess.db"
    
    # 数据库详细配置
    class DATABASE(BaseSettings):
        host: str = "maess_postgres"  # Docker容器名称
        port: int = 5432
        username: str = "admin"
        password: str = "admin"
        database: str = "maess_db"
        pool_size: int = 20
        max_overflow: int = 40
        pool_timeout: int = 30
        pool_recycle: int = 3600
        
        class Config:
            env_prefix = "DATABASE_"
            case_sensitive = False

    # Redis
    REDIS_URL: str = "redis://localhost:6379"
    REDIS_HOST: str = "localhost"
    REDIS_PORT: int = 6379
    REDIS_DB: int = 0
    REDIS_POOL_SIZE: int = 50
    REDIS_POOL_TIMEOUT: int = 10
    REDIS_SOCKET_TIMEOUT: int = 10
    REDIS_CONNECTION_RETRY: int = 3

    # 熔断器
    CIRCUIT_BREAKER_ENABLED: bool = True
    CIRCUIT_BREAKER_FAILURE_THRESHOLD: int = 5
    CIRCUIT_BREAKER_RECOVERY_TIMEOUT: int = 60
    CIRCUIT_BREAKER_HALF_OPEN_MAX_CALLS: int = 3

    # 分布式锁
    DISTRIBUTED_LOCK_ENABLED: bool = True
    DISTRIBUTED_LOCK_DEFAULT_TTL: int = 300
    DISTRIBUTED_LOCK_RENEW_INTERVAL: int = 60
    DISTRIBUTED_LOCK_RETRY_COUNT: int = 3
    DISTRIBUTED_LOCK_RETRY_DELAY: int = 1

    # 日志文件
    LOG_FORMAT: str = "json"
    LOG_FILE_PATH: str = "./logs/maess.log"
    LOG_FILE_MAX_SIZE: str = "100MB"
    LOG_FILE_BACKUP_COUNT: int = 10
    LOG_FILE_ROTATION: str = "midnight"

    # JWT
    JWT_SECRET_KEY: str = "maess-jwt-secret-key-for-development"
    JWT_ALGORITHM: str = "HS256"
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    JWT_REFRESH_TOKEN_EXPIRE_DAYS: int = 7

    # 搜索引擎
    SEARCH_ENGINE: str = "whoosh"
    SEARCH_INDEX_DIR: str = "./data/search_index"
    SEARCH_INDEX_REFRESH_INTERVAL: int = 300
    SEARCH_MAX_RESULTS: int = 100
    SEARCH_MIN_SCORE: float = 0.1

    # Prometheus
    PROMETHEUS_ENABLED: bool = True
    PROMETHEUS_HOST: str = "0.0.0.0"
    PROMETHEUS_PORT: int = 9090
    PROMETHEUS_METRICS_PATH: str = "/metrics"

    # 外部 Redis
    EXTERNAL_REDIS_HOST: str = "localhost"
    EXTERNAL_REDIS_PORT: int = 6379
    EXTERNAL_REDIS_DB: int = 1
    EXTERNAL_REDIS_POOL_SIZE: int = 20

    # 外部 API
    EXTERNAL_API_HOST: str = "localhost"
    EXTERNAL_API_PORT: int = 8080
    EXTERNAL_API_TIMEOUT: int = 30
    EXTERNAL_API_RETRY_COUNT: int = 3
    EXTERNAL_API_RETRY_DELAY: int = 1

    # 功能开关
    SEARCH_ENABLED: bool = True

    # Celery
    CELERY_BROKER_URL: str = "redis://localhost:6379/0"
    CELERY_RESULT_BACKEND: str = "redis://localhost:6379/0"
    CELERY_TASK_TIME_LIMIT: int = 300
    CELERY_TASK_SOFT_TIME_LIMIT: int = 240
    CELERY_WORKER_MAX_TASKS_PER_CHILD: int = 1000

    # 外部数据库
    EXTERNAL_DB_HOST: str = "localhost"
    EXTERNAL_DB_PORT: int = 3306
    EXTERNAL_DB_NAME: str = "maess_db"
    EXTERNAL_DB_USER: str = "root"
    EXTERNAL_DB_PASSWORD: str = "root"
    EXTERNAL_DB_POOL_SIZE: int = 10

    # RabbitMQ
    RABBITMQ_HOST: str = "localhost"
    RABBITMQ_PORT: int = 5672
    RABBITMQ_USER: str = "guest"
    RABBITMQ_PASSWORD: str = "guest"
    RABBITMQ_VHOST: str = "/"
    RABBITMQ_POOL_SIZE: int = 10
    RABBITMQ_CONNECTION_TIMEOUT: int = 10

    # Celery 详细配置
    CELERY_TASK_SERIALIZER: str = "json"
    CELERY_RESULT_SERIALIZER: str = "json"
    CELERY_ACCEPT_CONTENT: str = "json"
    CELERY_TIMEZONE: str = "Asia/Shanghai"
    CELERY_ENABLE_UTC: bool = False
    CELERY_WORKER_CONCURRENCY: int = 4
    CELERY_WORKER_PREFETCH_MULTIPLIER: int = 1

    # 性能监控仪表板
    PERFORMANCE_DASHBOARD_HOST: str = "0.0.0.0"
    PERFORMANCE_DASHBOARD_PORT: int = 8090
    MONITORING_COLLECTION_INTERVAL: int = 30
    MONITORING_RETENTION_DAYS: int = 7
    
    # 备份系统配置
    # 基础备份配置
    BACKUP_ROOT_DIR: str = "./data/backups"
    BACKUP_RETENTION_DAYS: int = 7
    BACKUP_COMPRESS: bool = True
    BACKUP_MAX_SIZE_GB: int = 50
    
    # 数据库备份配置
    DB_BACKUP_ENABLED: bool = True
    DB_BACKUP_SCHEDULE: str = "0 3 * * *"  # 每天凌晨3点
    DB_BACKUP_TIMEOUT: int = 3600  # 1小时
    
    # Redis备份配置
    REDIS_BACKUP_ENABLED: bool = True
    REDIS_BACKUP_SCHEDULE: str = "0 4 * * *"  # 每天凌晨4点
    
    # 文件系统备份配置
    FS_BACKUP_ENABLED: bool = True
    FS_BACKUP_SCHEDULE: str = "0 5 * * *"  # 每天凌晨5点
    FS_BACKUP_DIRS: list = ["./data", "./uploads"]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # 初始化嵌套的DATABASE配置
        self.DATABASE = self.DATABASE()
    
    class Config:
        env_file = ".env"
        case_sensitive = True
        extra = "allow"

# 单例
settings = Settings()